// 权限控制工具
export interface UserInfo {
  id: string;
  name: string;
  role: 'admin' | 'user';
  permissions: string[];
  loginTime: string;
}

// 获取当前用户信息
export const getCurrentUser = (): UserInfo | null => {
  const userInfo = localStorage.getItem('userInfo');
  if (!userInfo || userInfo === 'undefined') return null;
  try {
    return JSON.parse(userInfo);
  } catch {
    return null;
  }
};

// 获取用户角色
export const getUserRole = (): string | null => {
  return localStorage.getItem('userRole');
};

// 检查用户是否有指定权限
export const hasPermission = (permission: string): boolean => {
  const user = getCurrentUser();
  if (!user) return false;
  
  // 管理员拥有所有权限
  if (user.role === 'admin') return true;
  
  return user.permissions.includes(permission);
};

// 检查用户是否有指定角色
export const hasRole = (role: string): boolean => {
  const userRole = getUserRole();
  return userRole === role;
};

// 检查用户是否已登录
export const isAuthenticated = (): boolean => {
  const token = localStorage.getItem('token');
  const userInfo = localStorage.getItem('userInfo');
  return !!(token && userInfo);
};

// 获取用户权限列表
export const getUserPermissions = (): string[] => {
  const user = getCurrentUser();
  return user ? user.permissions : [];
};

// 权限常量
export const PERMISSIONS = {
  USER_READ: 'user:read',
  USER_WRITE: 'user:write',
  USER_DELETE: 'user:delete',
  SETTINGS_READ: 'settings:read',
  SETTINGS_WRITE: 'settings:write',
} as const;

// 角色常量
export const ROLES = {
  ADMIN: 'admin',
  USER: 'user',
} as const; 